package com.biggabrotha {
  import mx.containers.Canvas;
  import mx.rpc.events.FaultEvent;
  import mx.rpc.events.ResultEvent;
  import mx.rpc.http.HTTPService;

  public class GooglePictureProvider extends Canvas implements PictureProvider {
    private static const googleajaxurl:String = "http://ajax.googleapis.com/ajax/services/search/images"
    private static const jsonservice:HTTPService = new HTTPService(googleajaxurl, googleajaxurl)
    private static const gir:GoogleImageRequest = new GoogleImageRequest()
    public static const alphabet:String = "abcdefghijklmnopqrstuvwxyz"
    private var _isWorking:Boolean;

    public function get isWorking():Boolean {
      return _isWorking
    }

    public function createNewRandomQueryString():String {
      var r:Number = createRandomNumberInInterval(alphabet.length)
      var c:String = alphabet.charAt(r)
      return c
    }

    public function createRandomNumberInInterval(interval:Number):Number {
      return Math.round(Math.random() * interval - 1)
    }

    public function GooglePictureProvider() {
      jsonservice.method = "GET"
      jsonservice.request = gir
      jsonservice.requestTimeout = 10
      jsonservice.addEventListener(ResultEvent.RESULT, girResultHandler)
      jsonservice.addEventListener(FaultEvent.FAULT, girFaultHandler)
    }

    private function girResultHandler(e:ResultEvent):void {
      trace(e.result)
      _isWorking = true
    }

    private function girFaultHandler(e:ResultEvent):void {
      trace(e.result)
      _isWorking = true
    }

    public function set queryString(q:String):void {
      gir.q = q;
    }

    public function send() {
      jsonservice.send()
    }
  }
}